import cn.com.zhbs.netty.utils.ServerUtil;
import protobuf.Login;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.zip.CRC32;

/**
 * @author 陈治杰
 * @Title: Client
 * @Description: socket客户端
 * @date 2020/4/28 14:59
 */
public class Client extends Thread {

    //定义一个Socket对象
    Socket socket = null;

    public Client(String host, int port) {
        try {
            //需要服务器的IP地址和端口号，才能获得正确的Socket对象
            socket = new Socket(host, port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        //客户端一连接就可以写数据个服务器了
        new sendMessThread().start();
        super.run();
        try {
            // 读Sock里面的数据
            InputStream s = socket.getInputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = s.read(buf)) != -1) {
                System.out.println(new String(buf, 0, len));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //往Socket里面写数据，需要新开一个线程
    class sendMessThread extends Thread{
        @Override
        public void run() {
            super.run();
            //写操作
            OutputStream os= null;
            try {
                os= socket.getOutputStream();
                Login.C2S_Login.Builder builder=Login.C2S_Login.newBuilder();
                builder.setAccount("11111111111");
                builder.setPassword("123456");
                final Login.C2S_Login accountInfo=builder.build();

                byte[] s_data = new byte[accountInfo.toByteArray().length + 4];
                byte[] s_id= ServerUtil.short2Byte((short) 0);
                int len= 2+accountInfo.toByteArray().length;
                byte[] s_length = ServerUtil.short2Byte((short)len );
                System.arraycopy(s_length, 0, s_data, 0, s_length.length);
                System.arraycopy(s_id, 0, s_data, 2, s_id.length);
                System.arraycopy(accountInfo.toByteArray(), 0, s_data, 4, accountInfo.toByteArray().length);

                os.write(s_data);
                os.flush();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //函数入口
    public static void main(String[] args) throws NoSuchMethodException {

        Client clientTest=new Client("localhost", 3563);
        clientTest.start();
    }

}